/**
 * @(#)com.typrotech.cloudplatform.sys.controller.UpLoadController
 *
 * Copyright (c) 2014-2018 上海天跃科技有限公司
 *
 * DESC:
 *
 */
package com.framework.web.sys.controller;

import com.framework.core.util.FileUtils;
import com.framework.core.util.Persistence;
import com.framework.web.common.domain.Constants;
import com.framework.web.common.domain.ImgCompress;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Properties;
import java.util.UUID;

/**
 * 文件上传统一方法
 * @author fusf
 * @version 1.0  2015/10/30
 */
@Controller
public class UpLoadController {

    private static final Logger logger = Logger.getLogger(UpLoadController.class);

    /**
     *  普通的上传图片
     * @param request
     * @param response
     * @param file
     * @return
     */
    @RequestMapping(value = "/sys/upload/add", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String upLoadFile(HttpServletRequest request, HttpServletResponse response, MultipartFile file) throws Exception {
        String fileName = "";
        if (!file.isEmpty()) {
            if (file.getSize() > 5 * 1024 * 1024) {
                return "0";
            }
            String realPath = Persistence.getValue(getSystemPath());
            // 指向将要输出目标位置的文件目录
            File f = new File(realPath);
            if (!f.isDirectory()) {
                // 如果目标文件夹不存在，创建文件夹
                f.mkdirs();
            }
            fileName = UUID.randomUUID().toString()+".JPG";
            String fileLocation = realPath + "/" + fileName;
            // 将上传的文件放到应用目标路径下
            file.transferTo(new File(fileLocation));
        }
        return fileName;
    }

    /**
     *  上传的文件中要生成缩列图
     * @param request
     * @param response
     * @param file
     * @return
     */
    @RequestMapping(value = "/sys/upload/addDiagram", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String upLoadFile_shrink_diagram(HttpServletRequest request, HttpServletResponse response, @RequestParam("fileToUpload") MultipartFile file) throws Exception {
        String fileName = "";
        if (!file.isEmpty()) {
            if (file.getSize() > 5 * 1024 * 1024) {
                return "0";
            }
            String realPath = Persistence.getValue(getSystemPath());
            // 指向将要输出目标位置的文件目录
            File f = new File(realPath);
            if (!f.isDirectory()) {
                // 如果目标文件夹不存在，创建文件夹
                f.mkdirs();
            }
            //原图
            String fileName_real = UUID.randomUUID().toString() + ".JPG";
            String fileLocation = realPath + "/" + fileName_real;
            // 将上传的文件放到应用目标路径下
            file.transferTo(new File(fileLocation));
            //缩略图
            String fileName_small = UUID.randomUUID().toString() + ".JPG";
            String fileLocation_small = realPath + "/" + fileName_small;
            ImgCompress img = new ImgCompress(fileLocation, fileLocation_small);
            img.resizeFix(Constants.THUMBNAIL_WIDTH, Constants.THUMBNAIL_HEIGHT);
            fileName = fileName_small + "@" + fileName_real;//按  缩列图@原图  这种方式保存
        }
        return fileName;
    }



    /**
     * 根据系统来换取路径
     *
     * @return
     */
    private String getSystemPath() {
        //判断系统类型
        Properties prop = System.getProperties();
        String os = prop.getProperty("os.name");
        if (os.startsWith("win") || os.startsWith("Win")) {
            return Constants.UPLOADFILE;
        }
        return Constants.LINUX_UPLOADFILE;
    }

    /**
     * 批量上传图片
     * @param request
     * @param response
     * @param files
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/sys/upload/list",method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String upLoadFile_list(HttpServletRequest request,
                                  HttpServletResponse response,
                                  @RequestParam("fileToUpload") ArrayList<MultipartFile> files) throws Exception {
        String realPath = Persistence.getValue(getSystemPath());
        String imgNames = null;

        if (files.get(0).isEmpty()||files.get(0).getSize()==0) {
            return "0";
        } else if (!files.isEmpty()) {
            for (MultipartFile multipartFile : files) {
                if (multipartFile.getSize() > 5 * 1024 * 1024) {
                    return "1";
                }
            }
            String fileName = null;
            String fileType = null;
            StringBuffer imgUrl = new StringBuffer("");
            InputStream inputStream = null;
            for (MultipartFile multipartFile : files) {
                fileType = FileUtils.getFileType(multipartFile.getOriginalFilename());
                //文件名  uuid生成
                fileName = FileUtils.getUUID() + fileType;
                imgUrl.append(fileName);
                imgUrl.append(",");
                inputStream = multipartFile.getInputStream();
                File file = new File(realPath, fileName);
                //判断文件夹是否存在，不存在就创建
                if(!file.getParentFile().exists()){
                    File parent = file.getParentFile();
                    parent.mkdirs();
                }
                org.apache.commons.io.FileUtils.copyInputStreamToFile(inputStream, file);
            }
            int Length = imgUrl.length();
            imgNames = imgUrl.substring(0, Length - 1);
        }
        return imgNames;
    }


}
